var app = new Vue({
  el: "#app",
  data: {
    title: "chat",
    loading: false,
    user: "",
    userFlag: false,
    userStr: "",
    url: "wss://apk.yywis.com:9989/ws",
    // url: "ws://localhost:9605/ws",
    socket: null,
    messages: [],
    clients: {},
    userArr: []
  },

  mounted() {
    // this.getClients()
  },

  methods: {
    async init() {
      // this.loading = true;

      // let flag = await this.initClient();

      // if (flag) {
      //   this.$notify({
      //     title: "成功",
      //     message: "连接服务器成功",
      //     type: "success",
      //   });
      //   this.loading = false;
      // } else {
      //   this.$notify.error({
      //     title: "错误",
      //     message: "连接服务器失败",
      //   });
      // }
    },

    async initClient(user) {
      try {
        this.socket = new WebSocket(this.url + "?name=" + this.user);
        // event
        this.socket.onopen = this.onopen
        this.socket.onmessage = this.onmessage
        // this.sendMessage(true)
        this.getClients()
        return true;
      } catch (error) {
        return false;
      }
    },

    // 设置昵称
    async setUser() {
      if (!checkData(this.user)) {
        this.$notify({
          type: "warning",
          title: "法克",
          message: "昵称不可为空!",
        });
        return;
      }

      this.loading = true;

      let user = this.user;

      let flag = await this.initClient(user);

      if (flag) {
        // this.$notify({
        //   title: "成功",
        //   message: "连接服务器成功",
        //   type: "success",
        // });
        this.userFlag = true;
        this.loading = false;
      } else {
        this.$notify.error({
          title: "错误",
          message: "连接服务器失败",
        });
      }


    },

    // 本地添加
    async addMsg(json) {
      console.log("send");

      let ele = {
        name: json.name,
        content: json.content || "--",
        me: json.name == this.user.trim() ? true : false,
      };

      this.messages.push(ele);

      this.scrollBottom()

    },

    // 接收参数
    onmessage(e) {
      // console.log(e.data);
      let json = JSON.parse(e.data) || false
      if (!json) return
      if (!json.flag) {
        this.userFlag = false
        // console.log(json.content);
        this.$notify.error({
          title: "错误",
          message: json.content,
        });
        return
      }

      // console.log(json);
      let type = json.type
      switch (type) {
        case "login":
          this.clients[json.id] = json
          break;
        case "logout":
          delete this.clients[json.id]
          break;
      
        default:
          break;
      }
      this.addMsg(json)
    },

    // 发送参数
    async sendMessage(content) {

      let msg = this.userStr.trim()
      if (!checkData(msg)) {
        this.$notify({
          type: "warning",
          title: "法克",
          message: "内容不可为空!",
        });
        return;
      }

      let json = {
        name: this.user,
        content: msg
      }

      try {
        let ret = await this.socket.send(JSON.stringify({ json }))
        // console.log(ret);
      } catch (error) {
        this.$notify.error({
          title: "错误",
          message: "连接中断，请刷新浏览器重新连接",
        });
        return
      }

      this.userStr = ""
      this.$refs.msg.focus()
    },

    // get clients
    async getClients() {
      // setInterval(async () => {
      //   let ret = await myPost("/ws/clients")
      //   // console.log(ret.data.json);
      //   this.clients = ret.data.json
      // }, 1000);
      let ret = await myPost("/ws/clients")
      // console.log(ret.data.json);
      this.clients = ret.data.json
    },

    // key up
    keyUp(ev) {
      let oEvent = ev || event;
      if (oEvent.ctrlKey && oEvent.keyCode===13) {
        this.sendMessage()
      }
    },

    // 不常用方法.....
    onopen() {
      console.log('open...');
    },
    onerror() {
      console.log('err...');
    },

    scrollBottom() {
      this.$nextTick(() => {
        let div = document.getElementById("message");
        div.scrollTop = div.scrollHeight;
      });
    }

  },

  destroyed() {
    this.socket.send(JSON.stringify({
      name: this.user,
      content: "我主动关闭了页面"
    }))
  },
});
